package m.jclecai.com.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.base.recyclerview.BaseRecyclerViewAdapter;
import m.jclecai.com.base.recyclerview.BaseViewHolder;
import m.jclecai.com.bean.IssueInfoBean;
import m.jclecai.com.bean.common.MissDataTrendBean;
import m.jclecai.com.bean.common.TrendItemView;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.inter.OnResultCallback;
import m.jclecai.com.pop.KLSFPopWindow;
import m.jclecai.com.ui.BetConfirmActivity;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.OkHttpClientManager;
import m.jclecai.com.utils.ToastUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;

/**
 * 这里个是欲出率的一个Activity;
 */
public class ProbabilityOfCodeActivity extends BaseActivity {

    @BindView(R.id.rv_list)
    RecyclerView mRvList;

    @BindView(R.id.ll_layout)
    LinearLayout mLlLayout;

    int randomNumber;
    @BindView(R.id.tv_term)
    TextView mTvTerm;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.iv_date_unfold)
    ImageView mIvDateUnfold;
    @BindView(R.id.ll_date)
    LinearLayout mLlDate;

    //这里是footer里面的控件
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;
    @BindView(R.id.tv_number_money)
    TextView mTvNumberMoney;
    @BindView(R.id.tv_sure)
    TextView mTvSure;


    private ItemAdapter mItemAdapter;
    private String mType;

    //mCurrentMode对应的是当前的玩法；
    private KLSFPopWindow mCenterPopWindow;
    private int mCurrentMode;

    //listener;
    TrendItemView.OnCodeChosedLisener mListener;

    String[] playModes = new String[]{"任选二", "任选三", "任选四", "任选五", "任选六", "任选七", "任选八", "前二组选", "前三组选"};
    private CountDownTimer timer;
    private String mPlayMode;

    @Override
    protected int getContentView() {
        return R.layout.activity_probability_of_code;
    }

    @Override
    protected void initView() {
        super.initView();

        setTitle("欲出率");
        leftOptionText("");
        rightOptionText("",R.drawable.chart_help_default);
        setTitle("任选二", R.drawable.gs);

        mIvDateUnfold.setVisibility(View.INVISIBLE);

        initCenterPopupWindow();
    }

    /**
     * 初始化中间的popupwindow里面的内容；
     */
    private void initCenterPopupWindow() {

        mCenterPopWindow = new KLSFPopWindow(this);
        mCenterPopWindow.setOnItemClickListener(new KLSFPopWindow.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //这里我们执行的逻辑就是根据相应的position显示具体的界面；
                if (mCurrentMode != position) {
                    mCurrentMode = position;
                    setTitle(playModes[mCurrentMode]);
                    requestData();
                }
            }
        });
        mCenterPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                startAnimation(ivTitleIcon, R.anim.rotate_180_360);
            }
        });

    }



    @Override
    protected void initData() {
        super.initData();
        mType = getIntent().getStringExtra("type");
        mPlayMode = getIntent().getStringExtra("playMode");

        mRvList.setLayoutManager(new LinearLayoutManager(this));
        mItemAdapter = new ItemAdapter(null);
        mRvList.setAdapter(mItemAdapter);

        mCenterPopWindow.setItemData(Arrays.asList(playModes));

        mCurrentMode = playModeToPostion(mPlayMode);
        mCenterPopWindow.setPostionChecked(mCurrentMode);

        setTitle(playModes[mCurrentMode]);
        requestData();
        getIssueInfo(mType);
    }

    private int playModeToPostion(String playMode) {
        return Arrays.asList(playModes).indexOf(playMode);
    }


    private void getIssueInfo(String type) {
        OkHttpClientManager.Param Url = new OkHttpClientManager.Param("url", Constant_Url.ISSUE_INFO);
        OkHttpClientManager.Param Type = new OkHttpClientManager.Param("type", type);
        OkHttpClientManager.Param[] param = new OkHttpClientManager.Param[]{Url, Type};
        try {
            OkHttpClientManager.getInstance().asynPost(new OnResultCallback() {
                @Override
                public void onGetResult(String json) {
                    IssueInfoBean bean = FastOk.get(json, IssueInfoBean.class);
                    setViewInfo(bean);
                }

                @Override
                public void onError() {
                    ToastUtil.showToast(ProbabilityOfCodeActivity.this, R.string.connect_failure);
                }
            }, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setViewInfo(IssueInfoBean bean) {
        if (bean == null) return;
        try {
            String term = bean.getTermNo();
            //获取当前时间
            String currentTime = BaseUtils.getCurrentTime();
            //获取截止投注时间和当前时间的差值
            long m = BaseUtils.contrastDate(bean.getStopSaleTime(), currentTime, 2);
            long s = BaseUtils.contrastDate(bean.getStopSaleTime(), currentTime, 3);
            long time = m * 60 + s;
            String str = term.substring(term.length() - 2, term.length());
            mTvTerm.setText("距" + str + "期截止");
            startCountDownTime(Long.parseLong(bean.getDeadLine()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void startCountDownTime(final long time) {
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                mTvDate.setText(BaseUtils.formatDateLineToString(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                mTvDate.setText("已截止");
                getIssueInfo(mType);
            }
        };
        timer.start();// 开始计时
    }

    @Override
    protected void initListener() {
        super.initListener();

        mListener=new TrendItemView.OnCodeChosedLisener() {
            @Override
            public void onCodeChosed() {
                //这里我们进行一个刷新的操作；
                int number = mItemAdapter.getSelectedMissCodesTrendBean().size();
                mTvNumberMoney.setText(number+"注,"+number*2+"元");
            }
        };
        mIvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里清空所有选中的条目；
                for (MissDataTrendBean.MisscodesTreanBean misscodesTreanBean : mItemAdapter.getSelectedMissCodesTrendBean()) {
                    misscodesTreanBean.setSelected(false);
                }
                mItemAdapter.notifyDataSetChanged();
            }
        });
        //进行一个跳转到投注的界面
        mTvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToBetComfirm();
            }
        });

        tvMidTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //titlle的点击事件；
                startAnimation(ivTitleIcon, R.anim.rotate_0_180);
                mCenterPopWindow.showAsDropDown(rlBar);
            }
        });

        tvRightOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出一个对画框；
                AlertDialog.Builder builder = new AlertDialog.Builder(ProbabilityOfCodeActivity.this);
                builder.setTitle("参考说明");

                String message=" 当前遗漏：该号码自上次开出之后的连续未开出期数。\n" +
                        " 平均遗漏：是指所有遗漏值的平均值。\n" +
                        " 最大遗漏：该号码历史上的遗漏最大值。\n" +
                        " 欲出几率：当前遗漏÷平均遗漏";
                builder.setMessage(message);
                builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        });
    }

    private void jumpToBetComfirm() {

        ArrayList<String> ballNumber = new ArrayList<>();
        ArrayList<String> numMoney = new ArrayList<>();
        ArrayList<String> mode = new ArrayList<>();

        //讲数据进行一个封装
        List<MissDataTrendBean.MisscodesTreanBean> selectedMissCodesTrendBean = mItemAdapter.getSelectedMissCodesTrendBean();
        //这里我们将数据进行一个添加；
        for (MissDataTrendBean.MisscodesTreanBean misscodesTreanBean : selectedMissCodesTrendBean) {
            System.out.println("code: " + misscodesTreanBean.getCodes());
            String codes = misscodesTreanBean.getCodes();
            ballNumber.add(codes.replace(",", " "));
        }

        for (int i = 0; i < ballNumber.size(); i++) {
            numMoney.add("1注 2元");
            mode.add(playModes[mCurrentMode]);
        }

        Intent intent = new Intent(ProbabilityOfCodeActivity.this, BetConfirmActivity.class);
        intent.putExtra("type", mType); //彩种
        intent.putExtra("number", Integer.parseInt(getFlag())); //个数
        intent.putExtra("totalMoney", selectedMissCodesTrendBean.size() * 2); //总金额
        intent.putExtra("totalNum", selectedMissCodesTrendBean.size());
        intent.putStringArrayListExtra("ballNumber", ballNumber); //球
        intent.putStringArrayListExtra("mode", mode); //玩法及模式
        intent.putStringArrayListExtra("numMoney", numMoney); //注数及金额
        startActivityForResult(intent, 0);
    }

    private void requestData() {

        showDialog();

        HashMap<String, String> paramsMap = new HashMap<>();

        paramsMap.put("type", mType);
        paramsMap.put("flag", getFlag());

        HttpManager.postAsyn(Constant_Url.OUT_PERCENT, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {
                    //这里我们对其进行一个解析；
                    MissDataTrendBean missDataTrendBean = FastOk.get(response, MissDataTrendBean.class);
                    if (missDataTrendBean.getStatus().equals("0")) {
                        mItemAdapter.refresh(missDataTrendBean.getMisscodes());
                        closeLoadingLayout();
                    } else {
                        DisPlay(missDataTrendBean.getMessage());
                        showInternetOffLayout();
                    }
                } else {
                    DisPlay("网络连接异常！！！");
                    showInternetOffLayout();
                }
            }
        }, paramsMap);

    }

    private String getFlag() {
        //这里的这个方式是专门用来将mCurrentPosition转换为对应的Flag
        switch (mCurrentMode) {
            case 0:
                return "2";
            case 1:
                return "3";
            case 2:
                return "4";
            case 3:
                return "5";
            case 4:
                return "6";
            case 5:
                return "7";
            case 6:
                return "8";
            case 7:
                return "2";
            case 8:
                return "3";
        }
        return null;
    }

    @Override
    protected void resetWindow() {

    }



    public class ItemAdapter extends BaseRecyclerViewAdapter<MissDataTrendBean.MisscodesTreanBean> {


        public ItemAdapter(List<MissDataTrendBean.MisscodesTreanBean> DList) {
            super(DList);
        }

        @Override
        public int getItemView() {
            return R.layout.item_layout_probability_of_code;
        }

        @Override
        protected void bindViewHolder(BaseViewHolder holder, MissDataTrendBean.MisscodesTreanBean bean, int position) {
            TrendItemView itemView = (TrendItemView) holder.getView(R.id.tiv_trend_view);
            itemView.setData(bean);
            itemView.setOnCodeChosedLisener(mListener);
        }

        //获取用户用选中的条目；
        public List<MissDataTrendBean.MisscodesTreanBean> getSelectedMissCodesTrendBean() {
            ArrayList<MissDataTrendBean.MisscodesTreanBean> misscodesTreanBeen = new ArrayList<>();
            for (MissDataTrendBean.MisscodesTreanBean misscodesTreanBean : getDataList()) {
                if (misscodesTreanBean.isSelected()) {
                    misscodesTreanBeen.add(misscodesTreanBean);
                }
            }
            return misscodesTreanBeen;
        }
    }



}
